package com.security.manage.user.controller;

import com.security.manage.user.dto.ComboDto;
import com.security.manage.user.dto.UsbKeyDto;
import com.security.manage.user.model.*;
import com.security.manage.user.repository.UsbKeyRepository;
import com.security.manage.user.repository.UserRepository;
import com.security.manage.user.util.EntityUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api("uKey管理")
public class UsbKeyController {

    @Resource
    private UsbKeyRepository usbKeyRepository;

    @Resource
    private UserRepository userRepository;

    @PostMapping("/usbKey")
    public ResData addUsbKey(@RequestBody UsbKey usbKey){

        if (StringUtils.isEmpty(usbKey.getSnCode())|| StringUtils.isEmpty(usbKey.getSnNo())){
            return new ResData(0,"新增失败，参数异常");
        }
        if (usbKey.getCreateTime()==null){
            usbKey.setCreateTime(LocalDateTime.now());
        }
        usbKeyRepository.save(usbKey);
        return new ResData(1,"成功");
    }

    @DeleteMapping("/usbKey/{id}")
    public ResData delUsbKey(@PathVariable("id") Long id){

        Optional<UsbKey> role = usbKeyRepository.findById(id);
        if (role.isPresent()){
            UsbKey usbKey = role.get();
            User user = userRepository.findByUsbKey(usbKey.getSnCode());
            if (user!=null){
                return new ResData(0,"有用户关联了此UKey，不能删除");
            }
        }else {
            return new ResData(0,"此uKey不存在，不能删除");
        }
        usbKeyRepository.deleteById(id);
        return new ResData(1,"成功");
    }

    @GetMapping("/usbKey/{id}")
    public ResData getUsbKey(@PathVariable("id") Long id){
        Optional<UsbKey> role = usbKeyRepository.findById(id);
        return role.map(dept -> new ResData<>(1, "获取成功", dept)).orElseGet(() -> new ResData(0, "获取失败"));
    }

    @GetMapping("/usbKey/combo")
    public ResData usbKeyCombo(){
        List<Object[]> noBoundUsbKey = usbKeyRepository.getNoBoundUsbKey();
        List<ComboDto> comboDtos = new ArrayList<>();
        if (noBoundUsbKey==null|| noBoundUsbKey.size()==0){
            return new ResData(1,"没有数据",comboDtos);
        }
        try {
            List<UsbKeyDto> dtos = EntityUtil.castEntity(noBoundUsbKey, UsbKeyDto.class);
            return new ResData<>(1, "获取成功", dtos);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResData(0,"获取数据失败",null);
        }

    }

    @GetMapping("/usbKey/list")
    public ResData listUsbKey(@RequestParam(value = "page",defaultValue = "0") Integer page,
                            @RequestParam(value = "size",defaultValue = "10") Integer size){

        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest of = PageRequest.of(page, size, sort);
        Page<UsbKey> pages = usbKeyRepository.findAll(of);

        Map<String,Object> map = new HashMap<>();
        map.put("total",pages.getTotalElements());
        List<UsbKey> collect = pages.get().collect(Collectors.toList());
        List<User> users = userRepository.findAll();
        Map<String, String> usbKeyToUserName = users.stream().collect(Collectors.toMap(User::getUsbKey, User::getUserName));
        List<Map<String,Object>> resultList = new ArrayList<>();
        collect.forEach(usbKey -> {
            Map<String,Object> map1 = new HashMap<>();
            map1.put("id",usbKey.getId());
            map1.put("snCode",usbKey.getSnCode());
            map1.put("snNo",usbKey.getSnNo());
            map1.put("createTime",usbKey.getCreateTime());
            map1.put("userName",usbKeyToUserName.get(usbKey.getSnCode())==null?"":usbKeyToUserName.get(usbKey.getSnCode()));
            resultList.add(map1);
        });
        map.put("data",resultList);

        return new ResData<>(1, "获取成功", map);
    }
}
